package com.baixun.gascommon.utils;

import com.alibaba.fastjson.JSONObject;
import com.baixun.gasentity.vo.EvsApiLoginVO;

import java.util.Base64;
import java.util.HashMap;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @program: 上海燃气驾驶舱
 * @description:
 * @author: yesong
 **/
public class axcvvvvv {


    private static final String LOGIN ="/api/v2/login" ;
    private static final String  DOMAIN="https://evsretail.bce.baidu.com";

    private static final String  COOKIE_PREFIX="SAAS SESSION=";

    public static boolean evsLoginCurrent(){
        EvsApiLoginVO loginVO = new EvsApiLoginVO();
        loginVO.setPassword("Bx#evs@2024");
        loginVO.setName("project_admin_1");
        loginVO.setVerificationCodeToken("vcToken_VD3w8EYZ");
        loginVO.setVerificationCode("97fz");

        HashMap<String, String> headers = new HashMap<>();
        // 保持 Base64 拼接顺序：用户名 + API_SECRET + 密码
        String base64String = loginVO.getName() + "dspz5nGD" + loginVO.getPassword();
        String encodedAuth = Base64.getEncoder().encodeToString(base64String.getBytes(StandardCharsets.UTF_8));

        // 设置 Authorization 头为 Base64 编码的字符串
        headers.put("Authorization", encodedAuth);
        return postWithHeaders(DOMAIN + LOGIN, headers, JSONObject.toJSONString(loginVO));
    }

    private static boolean postWithHeaders(String url, HashMap<String, String> headers, String jsonString) {
        HttpURLConnection connection = null;
        try {
            // 创建 URL 对象
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 设置请求头
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 查找 Set-Cookie 字段中的 token
                Map<String, List<String>> responseHeaders = connection.getHeaderFields();
                String token = null;
                for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
                    // 查找 Set-Cookie 字段
                    if ("Set-Cookie".equalsIgnoreCase(entry.getKey())) {
                        for (String cookie : entry.getValue()) {
                            if (cookie.startsWith("SAAS_SESSION=")) {
                                // 提取 token 值
                                token = cookie.split(";")[0].split("=")[1];
                                break;
                            }
                        }
                    }
                }

                // 打印并返回 token
                if (token != null) {
                    System.out.println("Token: " + token);
                    return true;
                } else {
                    System.out.println("Token not found.");
                    return false;
                }
            } else {
                System.out.println("Request failed with response code: " + responseCode);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static boolean postAndPrintHeaders(String url, HashMap<String, String> headers, String jsonString) {
        HttpURLConnection connection = null;
        try {
            // 创建 URL 对象
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 设置请求头
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 打印请求头信息（在连接之前）
            System.out.println("Request Headers:");
            for (Map.Entry<String, List<String>> entry : connection.getRequestProperties().entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }

            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 打印响应头信息
            System.out.println("Response Headers:");
            for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return false;
    }



}
